import * as step from '@flow-step/step-toolkit'
import process from 'process'
import {installNode} from './install'
import * as util from './util'

const ENV_NAME_WORK_SPACE: string = 'PROJECT_DIR'
const ENV_NAME_VERSION_TYPE: string = 'VERSION_TYPE'
const ENV_NAME_NODE_VERSION_INPUT: string = 'CI_RUNTIME_VERSION'
const ENV_NPM_TYPE: string = 'NPM_TYPE'
const ENV_NAME_NODE_INSTALL_PATH: string = 'INSTALL_NODE_PATH'

async function runStep(): Promise<void> {
    const workSpace: string | undefined = process.env[ENV_NAME_WORK_SPACE]
    const versionType: string | undefined = process.env[ENV_NAME_VERSION_TYPE]
    const inputVersion: string | undefined = process.env[ENV_NAME_NODE_VERSION_INPUT]
    const npmType: string | undefined = process.env[ENV_NPM_TYPE]
    if (workSpace == undefined) {
        let errMsg = "Failed to get params 'WORK_SPACE'"
        throw new Error(errMsg)
    }
    if (npmType == undefined) {
        let errMsg = "Failed to get params 'NPM_TYPE'"
        throw new Error(errMsg)
    }
    const version = util.resolveVersion(workSpace, versionType, inputVersion)
    const installPath: string | undefined = process.env[ENV_NAME_NODE_INSTALL_PATH]
    await installNode(version, npmType, installPath)
}

runStep()
    .then(function () {
        step.success('run step successfully!')
    })
    .catch(function (err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
